// Spectrometer.cpp : Defines the entry point for the console application.
//

#include "sjOCU.h"


#pragma hdrstop
using namespace std;

//global variables
unsigned int nodeManagerCount;


extern char	Def_Address[MAX_ADDRESS_SIZE];


int main(int argc, char* argv[])
{
	OjCmpt myOCU;
	nodeManagerCount = 0;
	EnumWindows(EnumWindowsProc, 0);
	  if (nodeManagerCount == 0)
	  {
		  if (!(int) ShellExecute(NULL, L"open", L"ojNodeManager.exe", NULL, NULL, SW_SHOWNORMAL))
		  {
			  printf( "ShellExecute failed (%d)\n", GetLastError() );
		  }
		  else
		  {
			  wcout << "\n Node Manager loaded.\n" << endl;
			  Sleep(2000); //waiting loaded completed
		  }
	  }
	  else
	  {
		  wcout << "\n Node Manager has been opened.\n" << endl;
	  }
	wcout << endl << endl;

	//input address of lif
	printf("\nThe default science instrrument address: %s\n\nInput new address or k (keep):\n",DEF_ADDRESS);
	int ip[4]={0};
	cin >> Def_Address;
	if (sscanf_s(Def_Address,"%d.%d.%d.%d",&ip[0],&ip[1],&ip[2],&ip[3]) == 4)
	{
		sprintf_s(Def_Address,"%i.%i.%i.%i",ip[0],ip[1],ip[2],ip[3]);
	}
	else
	{
		strcpy(Def_Address,DEF_ADDRESS); //using default address
	}
	printf("\nThe address is %20s \n",Def_Address);

	myOCU = ocuCreate();
	if(myOCU == NULL)
	{
	   // Exit program
	   printf("Error Starting Component\n");
	   //return 1;
	}
	//star control
	printHelpMenu();
	for (;keyboardCTL(myOCU, 100););  //repeate every 100 ms


	ojCmptDestroy(myOCU);

 	return NULL;
}




BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam)	//Call Back Function For EnumWindows handle of every window to find whether a node manager started.
{
      
	  LPTSTR Buff = (LPTSTR)malloc(250);
	  int textlen, pos;
	  wstring title;
	  
	  
	  //wcout << "hWnd: " << hWnd << endl;
      textlen = GetWindowText(hWnd, Buff, 254);
	  title = Buff;
	  pos = title.find(L"ojNodeManager.exe");
      if (textlen > 0 && pos != -1)
	  {
		  wcout << "len:" << textlen  << "   Pos: " << pos << "   Title: " << title << endl;
		  nodeManagerCount++;
	  }

      return TRUE;
}

int keyboardCTL (OjCmpt OCU, int slp)
{
	// Console parameters
	HANDLE handleStdin = GetStdHandle(STD_INPUT_HANDLE);
    INPUT_RECORD inputEvents[128];
	DWORD eventCount;

	Sleep(slp);

	// See how many events are waiting for us, this prevents blocking if none
	GetNumberOfConsoleInputEvents(handleStdin, &eventCount);
	//printf("eventCount=%i\n",eventCount);

	if(eventCount > 0)
	{
		// Check for user input here
		ReadConsoleInput(
				handleStdin,		// input buffer handle
				inputEvents,		// buffer to read into
				128,				// size of read buffer
				&eventCount);		// number of records read
	}

	// Parse console input events
    for (int i = 0; i < (int) eventCount; i++)
    {
        //printf("EventType=%i\n",(int)inputEvents[i].EventType);
		switch(inputEvents[i].EventType)
        {
			case KEY_EVENT: // keyboard input
				if(inputEvents[i].Event.KeyEvent.wVirtualKeyCode == VK_ESCAPE)
				{
					//return false;   //exit stop
				}
				else if(inputEvents[i].Event.KeyEvent.bKeyDown)
				{
					if (parseUserInput(OCU, inputEvents[i].Event.KeyEvent.uChar.AsciiChar) == false) return false; 
				}				
			default:
				break;
		}
	}
	return true;
}

void printHelpMenu()
{
	printf("\n\nSciene Instrument JAUS OCU Help\n");
	printf("   s - Science Instrument Status\n");
	printf("   Q - Query Wave Length Data\n");
	printf("   c - Clear console window\n");
	printf("   ? - This Help Menu\n");
	printf("   e - Exit OCU LIF\n");
}
bool parseUserInput(OjCmpt OCU, char input)
{
	ocuData data = (ocuData) ojCmptGetUserData(OCU);
	wavelengthData si = data->wlData;
	int i;

	switch(input)
	{
		case 's':
			printf("\n\nstatus code=%i, address: %i.%i.%i.%i\n", data->lifState, 
				data->lifAddress->subsystem, data->lifAddress->node, data->lifAddress->component, data->lifAddress->instance);
			break;

		case 'Q':
			//printf("\n\n%s", nm->systemTreeToString().c_str());
			if (data->liveLIF && !data->queryImage)
			{
				data->queryImage = true;
				data->dataReady = false;		//mark flag
				data->queryTimeOut = time(NULL) + QUERY_IMAGE_TIMEOUT;
				ojCmptSetUserData(OCU,data);
				queryLIFdata(OCU);
			}
			break;

		case 'c':
			system("cls");
			break;

		case '?':
			printHelpMenu();
			break;

		case 'e':
			return false;

		default:
			break;
	}
	return true;
}

int writeData (wavelengthData siData)
{
	int Err=0;
	WCHAR fileName[32];
	HANDLE hFile; 

    char DataBuffer[2*LIF_WAVELENGTH_SIZE]; //JausunsignedShort 16bit

	int sizeofData = sizeof(DataBuffer);
	
	memcpy(DataBuffer,siData.wavelength, sizeofData);
	

    DWORD dwBytesToWrite = sizeofData;
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = FALSE;
	swprintf(fileName,sizeof(fileName),L"%i.ml",siData.ID);

    hFile = CreateFile((LPCWSTR)fileName,		// name of the write
                       GENERIC_WRITE,          // open for writing
                       0,                      // do not share
                       NULL,                   // default security
                       CREATE_NEW,             // create new file only
                       FILE_ATTRIBUTE_NORMAL,  // normal file
                       NULL);                  // no attr. template

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        printf("Terminal failure: Unable to open file \"%s\" for write.\n", fileName);
        return 1;
    }
    bErrorFlag = WriteFile( 
                    hFile,           // open file handle
                    DataBuffer,      // start of data to write
                    dwBytesToWrite,  // number of bytes to write
                    &dwBytesWritten, // number of bytes that were written
                    NULL);            // no overlapped structure

    if (FALSE == bErrorFlag)
    {
        printf("Terminal failure: Unable to write to file.\n");
		Err = 1;
    }
    else
    {
        if (dwBytesWritten != dwBytesToWrite)
        {
            // This is an error because a synchronous write that results in
            // success (WriteFile returns TRUE) should write all data as
            // requested. This would not necessarily be the case for
            // asynchronous writes.
            printf("Error: dwBytesWritten != dwBytesToWrite\n");
			Err = 1;
        }
        else
        {
            _tprintf(TEXT("\nWavelength data %d bytes save to %s successfully.\n"), dwBytesToWrite, fileName);
        }
    }
    CloseHandle(hFile);

	return Err;
}

